var contentNode = document.getElementById('content');

const TaskRow = (props) => {
    console.log(props.task);
    return (
        <tr>
            <td>{props.task.id}</td>
            <td>{props.task.companyName}</td>
            <td>{props.task.category}</td>
            <td>{props.task.createAt.toDateString()}</td>
        </tr>
    )
}

function TaskTable(props){
    const TaskRows = props.tasks.map(task => <TaskRow key={task.id} task={task} />)
    return(
        <table>
            <thead>
                <tr>
                    <td>Id</td>
                    <td>Name</td>
                    <td>category</td>
                    <td>Create</td>
                </tr>
            </thead>
            <tbody>
                { TaskRows }
            </tbody>
        </table>
    )
}

class TaskReview extends React.Component {
    constructor(){
        super();
        this.state = {tasks: []};
    }
    
    componentDidMount(){
        this.loadData();
    }

    loadData(){
        fetch('/api/tasks').then(response=>{
            return response.json()
        }).then(data => {
            console.log(data);
            data.records.forEach(task=>{
                task.createAt = new Date(task.createAt);
            })
            this.setState({tasks: data.records})
        }).catch(err=>{
            console.log('Load data has an error:' + err);
        })
    }

    render(){
        return (
            <div>
                <TaskTable tasks={this.state.tasks} />
            </div>
        )
    }
}

ReactDOM.render(<TaskReview />, contentNode);